// src/store/modules/userSlice.ts

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { RoleType, UserInfo } from "@types/store";
import api from "@api"; // 封装好的 Axios 实例
import { setToken, removeToken } from "@utils/auth";
import { message } from "antd";

// Async Thunk：用户登录
export const login = createAsyncThunk<
  { token: string }, // 返回值类型
  { username: string; password: string }, // 传入参数类型
  { rejectValue: string } // reject 类型
>("user/login", async (credentials, thunkAPI) => {
  try {
    const res = await api.post("/user/login", credentials);
    // 假设后端返回 { code: 200, data: { token: 'xxx' } }
    const { token } = res as any;
    setToken(token);
    return { token };
  } catch (error: any) {
    return thunkAPI.rejectWithValue(error.message);
  }
});

// Async Thunk：获取用户信息
export const fetchUserInfo = createAsyncThunk<
  UserInfo, // 返回值类型
  void, // 无需传入参数
  { rejectValue: string }
>("user/fetchUserInfo", async (_, thunkAPI) => {
  try {
    const res = await api.get("/user/info");
    // 假设后端返回 { code: 200, data: { username, avatar, roles } }
    return res as UserInfo;
  } catch (error: any) {
    return thunkAPI.rejectWithValue(error.message);
  }
});

interface UserState {
  token: string | null;
  username: string;
  avatar: string;
  roles: RoleType[];
  status: "idle" | "loading" | "failed";
}

const initialState: UserState = {
  token: localStorage.getItem("my_admin_token"),
  username: "",
  avatar: "",
  roles: [],
  status: "idle",
};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    // 同步 action：登出
    logout(state) {
      removeToken();
      state.token = null;
      state.username = "";
      state.avatar = "";
      state.roles = [];
    },
  },
  extraReducers: (builder) => {
    builder
      // login
      .addCase(login.pending, (state) => {
        state.status = "loading";
      })
      .addCase(
        login.fulfilled,
        (state, action: PayloadAction<{ token: string }>) => {
          state.status = "idle";
          state.token = action.payload.token;
        }
      )
      .addCase(login.rejected, (state, action) => {
        state.status = "failed";
        message.error(`登录失败：${action.payload}`);
      })

      // fetchUserInfo
      .addCase(fetchUserInfo.pending, (state) => {
        state.status = "loading";
      })
      .addCase(
        fetchUserInfo.fulfilled,
        (state, action: PayloadAction<UserInfo>) => {
          state.status = "idle";
          state.username = action.payload.username;
          state.avatar = action.payload.avatar;
          state.roles = action.payload.roles;
        }
      )
      .addCase(fetchUserInfo.rejected, (state, action) => {
        state.status = "failed";
        message.error(`获取用户信息失败：${action.payload}`);
      });
  },
});

export const { logout } = userSlice.actions;

// 选择器
export const selectUserToken = (state: any) => state.user.token;
export const selectUserName = (state: any) => state.user.username;
export const selectUserAvatar = (state: any) => state.user.avatar;
export const selectUserRoles = (state: any) => state.user.roles;

export default userSlice.reducer;
